# download http://www.9sct.com/chapter/2579/1355738.html -1355747
# curl -o /home/xieweig/document/10.txt http://www.9sct.com/chapter/2579/1355738.html
import subprocess

target_dir = '/home/xieweig/document/'


def a():
    url: str = 'http://www.9sct.com/chapter/2579/'

    cmd = ''
    for i in range(10):
        cmd = 'curl -o ' + target_dir + str(10 + i) + '.html ' + url + str(1355738 + i) + '.html'
        print(cmd)
        subprocess.run(cmd.split(' '))


def b():
    tar_dir = '/home/xieweig/document/'
    # tar -zcvf aa.tar.gz /home/xieweig/ducument/10.html 11.html ...
    m = [tar_dir + str(x + 10) + '.html' for x in range(10)]
    m.insert(0, 'tar')
    m.insert(1, '-zcvf')
    m.insert(2, tar_dir + 'aa.tar.gz')
    print(m)
    print(subprocess.list2cmdline(m))
    # k=subprocess.run(m)
    # with k.stdout as out:
    #     out.readline()
    # print(k.returncode)

    out = open(tar_dir + 'output.txt', mode='w')
    err = open(tar_dir + 'error.txt', mode='w')
    k = subprocess.Popen(m, stdout=out, stderr=err)
    k.communicate()


def c():
    # ls xxx | wc -i
    global target_dir
    print(target_dir[:-1])
    k = ['ls', target_dir]
    print('ls %s | wc -l' % target_dir)
    ss='ls {0} | wc -l'.format(target_dir).split(' ')
    print(subprocess.list2cmdline(ss))
    # s=subprocess.Popen(k,stdout=subprocess.PIPE,encoding='utf-8')
    # t=subprocess.Popen('wc -l'.split(' '),stdin=subprocess.PIPE
    #                    ,stdout=subprocess.PIPE,encoding='utf-8')
    # stdout, stderr = s.communicate()
    # print(stdout,type(stdout))
    # o,e=t.communicate(input=stdout)
    # print(o)

    # subprocess.run('wc -l'.split(),
    #                input=subprocess.run(k).stdout)

    subprocess.run('wc -l'.split(' '),
                   input=subprocess.run(k,stdout=subprocess.PIPE).stdout)



def d():
    p=subprocess.run('ls -lah {0}'.format(target_dir).split(' '),
                     stdout=subprocess.PIPE,encoding='utf-8')

    print(type(p.stdout), p.stdout)

    s:str = p.stdout
    r= [x.split(' ')[-1] for x in s.split('\n') if '.txt' in x]
    print(r)

d()
